
import java.sql.*;   // methods to process SQL commands
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

import javax.sql.*;  // ditto
//import org.postgresql.jdbc3.Jdbc3PoolingDataSource; // connection via JDBC to postgrSQL
import java.io.IOException;   // enable IOException objects & handling
import java.io.PrintWriter;   // enable PrintWriter (so can use .println())
import javax.servlet.http.*;  // provides servlet functionality
import javax.servlet.*;	      // ditto
import javax.*;


public class SearchForMovies extends HttpServlet
{
	//private static DataSource ds;	// contains DB and connection data; see init()
	private  Connection connection;
	//private static StringBuffer buf;
	private  boolean lastPage = false;
	private  int startIndex = 0;
	private int endIndex = 0;
	private int sizeOfList = 0;
	private HttpSession session;
	
	private static final boolean DEBUG = false;
	
	public  String issueQuery(String movieTitle, String year, String director, String featuredStars, HttpServletRequest request)
    {	
		StringBuffer buf2 = new StringBuffer();
		try 
		{
			//HttpSession session = request.getSession();
			
			MovieList movie_list = (MovieList) session.getAttribute(Constants.MovieListAttributeName);
			ResultSet resultMovie = null;
			
			if((request.getParameter("order") != null || request.getParameter("goTo") != null) && movie_list != null && movie_list.getQueryFeaturedStars().length() > 0)
				return (buf2.append(findFeaturedStars(request))).toString();
			
			if(request.getParameter("order") != null && (request.getParameter("order")).length() > 0)
			{	
				if(request.getParameter("order").equals(Constants.ORDER_BY_TITLE))
				{
					if(movie_list.getOrderType().equals(Constants.ORDER_BY_TITLE))
						movie_list.reverseOrder();
					else
					{
						movie_list.setOrderType(Constants.ORDER_BY_TITLE);
						//movie_list.order = Constants.ASCENDING;
					}
					
					Statement select21 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
					resultMovie = select21.executeQuery(movie_list.getQuery() + " ORDER BY title " + movie_list.getOrder() + ", year DESC");
					if (DEBUG) buf2.append("Looking for new order of same query : " +movie_list.getQuery() + " ORDER BY title " + movie_list.getOrder() + ", year DESC <br><br>");
					movie_list.setRS(resultMovie);
					movie_list.setStartIndex(0);
					
				}
				else if(request.getParameter("order").equals(Constants.ORDER_BY_YEAR) )
				{
					if(movie_list.getOrderType().equals(Constants.ORDER_BY_YEAR))
						movie_list.reverseOrder();
					else
					{
						movie_list.setOrderType(Constants.ORDER_BY_YEAR);
						//movie_list.order = Constants.ASCENDING;
					}
					
					Statement select22 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
					resultMovie = select22.executeQuery(movie_list.getQuery() + " ORDER BY year " + movie_list.getOrder());
					if (DEBUG) buf2.append("Looking for new order of same query : " +movie_list.getQuery() + " ORDER BY year " + movie_list.getOrder()+" <br><br>");
					movie_list.setRS(resultMovie);
					movie_list.setStartIndex(0);
				}
				else if(request.getParameter("order").equals(Constants.ORDER_BY_DIRECTOR) )
				{
					if(movie_list.getOrderType().equals(Constants.ORDER_BY_DIRECTOR))
						movie_list.reverseOrder();
					else
					{
						movie_list.setOrderType(Constants.ORDER_BY_DIRECTOR);
						//movie_list.order = Constants.ASCENDING;
					}
					
					Statement select23 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
					resultMovie = select23.executeQuery(movie_list.getQuery() + " ORDER BY director_last_name " + movie_list.getOrder() + ", year DESC");
					if (DEBUG) buf2.append("Looking for new order of same query : " +movie_list.getQuery() + " ORDER BY director_last_name " + movie_list.getOrder() + ", year DESC <br><br>");
	
					movie_list.setRS(resultMovie);
					movie_list.setStartIndex(0);
				}
				
				if(movie_list.getStart() == 0)
					movie_list.setStartIndex(0);
				
				movie_list.setState("firstPage");
				startIndex = movie_list.getStart();
				endIndex = startIndex + 20;
				session.setAttribute(Constants.MovieListAttributeName, movie_list);
			}
			else if(request.getParameter("goTo") != null)
			{
				
				String goTo = request.getParameter("goTo");
				if (DEBUG) buf2.append("doing go to: " + goTo + "<br><br>");
				
				startIndex = Integer.parseInt(request.getParameter("start"));
				endIndex = Integer.parseInt(request.getParameter("end"));
				movie_list.setStartIndex(startIndex);
				/*if( movie_list.getState().equals("lastPage"))
				{
				
					int sizeOfList = movie_list.getSizeOfMovieList();	
					buf2.append("RESULT OF GOING BACK FROM LAST PAGE: sizeOfList: " + sizeOfList);
					if(sizeOfList%20 == 0)
					{	buf2.append("size is mod by 20");
						movie_list.setStartIndex(sizeOfList - 40);
						int shouldStartAt = sizeOfList -40;
						buf2.append("movie list should be start at : " + shouldStartAt +"<br>");
						buf2.append("movie list actually starting at : " + movie_list.getStart() +"<br>");
					}
					else
					{
						int index = 0;
						while(index < sizeOfList)
						{
							index += 20;
						}
						movie_list.setStartIndex(index-40);
						
						if(index-40 != movie_list.getStart())
								buf2.append("start index does not match changes");
						
						buf2.append("CHANGED START INDEX: " + movie_list.getStart());
					}
					movie_list.setState("middlePage");
				}
				else if(goTo.equals(Constants.PREV))
				{
					buf2.append("before state: " + movie_list.getState());
					buf2.append("before - GOING TO PREVIOUS!! SHOULD START AT: " + movie_list.getStart() + "<br><br>");
					//int temp = start - 40;
					movie_list.setStartIndex(movie_list.getStart() - 40);
					buf2.append("after - GOING TO PREVIOUS!! SHOULD START AT: " + movie_list.getStart()+ "<br><br>");
					movie_list.setState("middlePage");
				}
				
				if(movie_list.getStart() < 0 || goTo.equals(Constants.BEGIN))
				{
					buf2.append("starting list again at zero");
					movie_list.setState("firstPage");
					movie_list.setStartIndex(0);
				}
				if(goTo.equals(Constants.NEXT))
				{
					buf2.append("GOING NEXT, starting with index: " + movie_list.getStart());
					movie_list.setState("middlePage");
				}
				*/
				session.setAttribute(Constants.MovieListAttributeName, movie_list);
				
				resultMovie = movie_list.getMovieList();
			}
			else if(movie_list == null || !(movie_list.getMovieListType().equals(Constants.SEARCHING)) 
					|| movieTitle != null || featuredStars != null || year != null || director != null)
			{
				if (DEBUG) buf2.append("Building new resultset list <br><br>");
				String first_director = "";
				String last_director = "";
				boolean oneName = false;
				if(director != null)
				{
					StringTokenizer tokenizer = new StringTokenizer(director);
					
					int countTokens = tokenizer.countTokens();
					if(countTokens == 1)
					{
						last_director = director;
						first_director = director;
						oneName = true;
					}
					else
					{
						while(tokenizer.hasMoreTokens())
						{
							countTokens--;
							if(countTokens == 0)
								last_director = tokenizer.nextToken();
							else
								first_director += tokenizer.nextToken() + " ";
										
						}
					}	
				}
				
				first_director= first_director.trim();
				last_director = last_director.trim();
				String query = "Select * from movies where ";
				int counterTemp = 0;
				int LEDAdistance = 0;
				if(movieTitle != null && movieTitle.length() > 0)
				{
					int titleLength = movieTitle.length();
					
					LEDAdistance = findDistanceLEDA(titleLength);
					query += " (title ILIKE " + "'%"+movieTitle+ "%' OR ISCLOSE(title, '"+movieTitle+"',"+LEDAdistance+"))";
					counterTemp++;
				}
				if(year != null && year.length()>0)
				{
					if(counterTemp != 1)
						query += " year = " + year;
					else
						query += " and year = " + year;
					
					counterTemp++;
				}
				if(last_director != null && last_director.length() >0)
				{
					int last_director_length = last_director.length();
					LEDAdistance = findDistanceLEDA(last_director_length);
					
					if(counterTemp == 0)
						query += " ( (director_last_name ilike '%" + last_director+ "%' OR ISCLOSE(director_last_name, '"+last_director+"', "+LEDAdistance+") )";
					else if(oneName)
						query += " and ( (director_last_name ilike '%" + last_director+ "%' OR ISCLOSE(director_last_name, '"+last_director+"', "+LEDAdistance+") )";
					else
						query += " and ( (director_last_name ilike '%" + last_director+ "%' OR ISCLOSE(director_last_name, '"+last_director+"', "+LEDAdistance+") )";					
					
					counterTemp++;
				}
				if(first_director != null && first_director.length() >0)
				{
					int first_director_length = first_director.length();
					LEDAdistance = findDistanceLEDA(first_director_length);
					
					if(counterTemp == 0)
						query += " director_rest_of_name ilike '%" + first_director+ "%'";
					else if(oneName)
						query += " or ( director_rest_of_name ilike '%" + first_director+ "%' OR ISCLOSE(director_rest_of_name, '"+first_director+"', "+LEDAdistance+") ) )";
					else
						query += " and ( director_rest_of_name ilike '%" + first_director+ "%' OR ISCLOSE(director_rest_of_name, '"+first_director+"', "+LEDAdistance+") ) )";
					
					counterTemp++;
				}
				if(counterTemp == 0)
					query = "Select * from movies";
				
				String tempString = query;
				query += " ORDER BY title, year DESC"; //make it order by title and then year desc.
				
				
				if (DEBUG) buf2.append("The query was: " + query + "<br><br>");
		
				// see the API doc at java.sun.com for details
					
				if(featuredStars != null && featuredStars.length() > 0)
					return (buf2.append(findFeaturedStars(query, featuredStars))).toString();
				
				
				Statement select6 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
				resultMovie = select6.executeQuery(query);
				
				movie_list = new MovieList();
				movie_list.setMovieListType( Constants.SEARCHING);
				movie_list.setRS(resultMovie);
				movie_list.setQuery ( tempString );
				movie_list.setState("firstPage");
				session.setAttribute(Constants.MovieListAttributeName, movie_list);
				startIndex = movie_list.getStart() ;
				endIndex = startIndex + 20;
			}
			
			if (DEBUG) buf2.append("movie list start: " + movie_list.getStart());
			
			resultMovie.absolute(movie_list.getStart());
			startIndex = movie_list.getStart();
			this.sizeOfList = movie_list.getSizeOfMovieList();
			
			//buf2.append("QUERY 3: " + movie_list.getQuery() +"<br><br>");
			if(movie_list.getQuery().equals("Select * from movies"))
			{
				buf2.append("No movies were found.");
				sizeOfList = 0;
				connection.close();
				return buf2.toString();
			}
			
			int counter = 0;
			
			while(counter <20 && resultMovie.next())
			{
				
				buf2.append("<TR valign=top>");
				buf2.append("<TD width=150><div class=\"wpmd\">");
				buf2.append("<div>");
				buf2.append("<input type=\"radio\" name=\"movieId\" value=\"" + resultMovie.getInt(1) + "\"> " + "<a href=\"SingleMovieTitle?id="+resultMovie.getInt(1)+"\"> " +resultMovie.getString(2) + "</a>");
				buf2.append("</div>");
				buf2.append("</TD>");
				
			
				buf2.append("<TD width=100><div class=\"wpmd\">");
				buf2.append("<div>");
				buf2.append( resultMovie.getInt(3));
				buf2.append("</div>");
				buf2.append("</TD>");
				
				
				buf2.append("<TD width=150><div class=\"wpmd\">");
				buf2.append("<div>");
				buf2.append(resultMovie.getString(7) + " "+ resultMovie.getString(4));
				buf2.append("</div>");
				buf2.append("</TD>");
				
				String genreAssociated = findGenres(Integer.toString(resultMovie.getInt(1)));
				//genres
				buf2.append("<TD width=150><div class=\"wpmd\">");
				buf2.append("<div>");
				buf2.append(genreAssociated);
				buf2.append("</div>");
				buf2.append("</TD>");
				

				String stars = findStars(Integer.toString(resultMovie.getInt(1)));
				//movie stars
				buf2.append("<TD width=200><div class=\"wpmd\">");
				buf2.append("<div>");
				buf2.append(stars);
				buf2.append("</div>");
				buf2.append("</TD>");
				
				buf2.append("</TR>");
				counter++;
				
				if(resultMovie.getRow() == endIndex)
					counter = 20;
	
			}	
			
			if(!resultMovie.isAfterLast() && counter == 20)
			{
				if (DEBUG) buf2.append("middle page or beginning page");
				movie_list.setStartIndex(resultMovie.getRow());
				lastPage = false;
			}
			if((resultMovie.isLast() &&  counter == 20) || resultMovie.isAfterLast())
			{		
				int tempInt = movie_list.getStart() + 20;
				movie_list.setStartIndex(tempInt);
				if (DEBUG) buf2.append("last page! Ending list at: " + tempInt);
				if (DEBUG) buf2.append("last page set start index: " + movie_list.getStart());
				lastPage = true;
				movie_list.setState("lastPage");
			}
		
			if (DEBUG) buf2.append("Ending list at : " + movie_list.getStart());
			if(movie_list.getStart() == 0)
			{
				buf2.append("<font color=\'red\'> Your search has zero results. </font><br>");
				return buf2.toString();
			}
			session.setAttribute(Constants.MovieListAttributeName, movie_list);
			
			connection.close();
				
		}
		catch(NullPointerException e)
		{
			buf2.append("NullPointerException occured: " + e.getMessage() + "\n" + e.getStackTrace());
			
		}
		catch (SQLException sqle)
		{
			buf2.append("SQL exception occured: " + sqle.getMessage());
		}		
		
		// return buffered string of text
		
		return buf2.toString();
	}
	
	private int findDistanceLEDA(int sourceString) {
		if(sourceString < 2)
			return 0;
		if(sourceString < 5)
			return 1;
		if(sourceString < 10)
			return sourceString/3;
		
		return sourceString/2;
	
	}

	public  String findGenres(String movieId) throws SQLException
	{
		Statement select4 = connection.createStatement();
		ResultSet resultGenresID = select4.executeQuery("Select genre_id from genres_in_movies where movie_id = " + movieId);
		String temp = "";
		while(resultGenresID.next())
		{
			Statement select5 = connection.createStatement();
			ResultSet resultGenres = select5.executeQuery("Select * from genres where id = " + resultGenresID.getInt(1));
			if(resultGenres.next())
				temp += resultGenres.getString(2) + " <br>";
			
			//select5.close();
		}
		
		//select4.close();
		if(temp.equals(""))
			return "No genres";
		
		
		return temp;	
	}
	public String findFeaturedStars(HttpServletRequest request)
	{
		StringBuffer buf2 = new StringBuffer();
		if (DEBUG) buf2.append("INSIDE FEATURED STARS OLD <br><br>");
		MovieList movie_list = (MovieList) session.getAttribute(Constants.MovieListAttributeName);
		ResultSet resultMovies = null;
		ResultSet resultMoviesMatchingStars = null;
		String tempQueryFeaturedStars = "";
		try
		{
			if(request.getParameter("order") != null && (request.getParameter("order")).length() > 0)
			{	
				if(request.getParameter("order").equals(Constants.ORDER_BY_TITLE))
				{
					if(movie_list.getOrderType().equals(Constants.ORDER_BY_TITLE))
						movie_list.reverseOrder();
					else
					{
						movie_list.setOrderType(Constants.ORDER_BY_TITLE);
						//movie_list.order = Constants.ASCENDING;
					}
					
					Statement select40 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
					resultMoviesMatchingStars = select40.executeQuery(movie_list.getQueryFeaturedStars() + " ORDER BY title " + movie_list.getOrder() + ", year DESC");
					if (DEBUG) buf2.append("Looking for new order of same query : " +movie_list.getQueryFeaturedStars() + " ORDER BY title " + movie_list.getOrder() + ", year DESC <br><br>");
					movie_list.setRSFeaturedStars(resultMoviesMatchingStars);
					movie_list.setStartIndex(0);
					
				}
				else if(request.getParameter("order").equals(Constants.ORDER_BY_YEAR) )
				{
					if(movie_list.getOrderType().equals(Constants.ORDER_BY_YEAR))
						movie_list.reverseOrder();
					else
					{
						movie_list.setOrderType(Constants.ORDER_BY_YEAR);
						//movie_list.order = Constants.ASCENDING;
					}
					
					Statement select41 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
					resultMoviesMatchingStars = select41.executeQuery(movie_list.getQueryFeaturedStars() + " ORDER BY year " + movie_list.getOrder());
					if (DEBUG) buf2.append("Looking for new order of same query : " +movie_list.getQueryFeaturedStars() + " ORDER BY year " + movie_list.getOrder()+" <br><br>");
					movie_list.setRSFeaturedStars(resultMoviesMatchingStars);
					movie_list.setStartIndex(0);
				}
				else if(request.getParameter("order").equals(Constants.ORDER_BY_DIRECTOR) )
				{
					if(movie_list.getOrderType().equals(Constants.ORDER_BY_DIRECTOR))
						movie_list.reverseOrder();
					else
					{
						movie_list.setOrderType(Constants.ORDER_BY_DIRECTOR);
						//movie_list.order = Constants.ASCENDING;
					}
					
					Statement select42 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
					resultMoviesMatchingStars = select42.executeQuery(movie_list.getQueryFeaturedStars() + " ORDER BY director_last_name " + movie_list.getOrder() + ", year DESC");
					if (DEBUG) buf2.append("Looking for new order of same query : " +movie_list.getQueryFeaturedStars() + " ORDER BY director_last_name " + movie_list.getOrder() + ", year DESC <br><br>");
	
					movie_list.setRSFeaturedStars(resultMoviesMatchingStars);
					movie_list.setStartIndex(0);
				}
				
				if(movie_list.getStart() == 0)
					movie_list.setStartIndex(0);
				
				movie_list.setState("firstPage");
				startIndex = movie_list.getStart();
				endIndex = startIndex + 20;
				session.setAttribute(Constants.MovieListAttributeName, movie_list);
				resultMovies = movie_list.getMovieList();
				resultMoviesMatchingStars = movie_list.getMovieListFeaturedStars();
			}
			else if(request.getParameter("goTo") != null)
			{
				
				String goTo = request.getParameter("goTo");
				if (DEBUG) buf2.append("doing go to: " + goTo + "<br><br>");
				
				startIndex = Integer.parseInt(request.getParameter("start"));
				endIndex = Integer.parseInt(request.getParameter("end"));
				movie_list.setStartIndex(startIndex);
				
				session.setAttribute(Constants.MovieListAttributeName, movie_list);
				tempQueryFeaturedStars = movie_list.getQueryFeaturedStars();
				
				resultMovies = movie_list.getMovieList();
				resultMoviesMatchingStars = movie_list.getMovieListFeaturedStars();
				if (DEBUG) buf2.append("QUERY FOR FEATURED STARS: " + tempQueryFeaturedStars);
				//resultMovie = movie_list.getMovieList();
			}
			
			//Statement select30 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			//resultMoviesMatchingStars = movie_list.getMovieListFeaturedStars();
			if (DEBUG) buf2.append("passed query ok");
			//Statement select11 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			
			
			//Statement select31 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			//resultMovies= select31.executeQuery(movie_list.getQuery());
			//buf2.append("passed original query ok");
			//resultMovies = movie_list.getMovieList();
			//resultMovies.beforeFirst();

			session.setAttribute(Constants.MovieListAttributeName, movie_list);
		
			startIndex = movie_list.getStart() ;
			endIndex = startIndex + 20;
			
			if(movie_list.getQuery().equals("Select * from movies") || movie_list.getQueryFeaturedStars().equals("Select * from movies"))
			{
				buf2.append("No movies were found.");
				sizeOfList = 0;
				connection.close();
				return buf2.toString();
			}
			
			if (DEBUG) buf2.append("passed checking for empty queries ok");
			resultMoviesMatchingStars.last();
			this.sizeOfList = resultMoviesMatchingStars.getRow();
			if (DEBUG) buf2.append("passed sizeoflist calculations");
			resultMoviesMatchingStars.absolute(movie_list.getStart());
			resultMovies.beforeFirst();
			int counter = 0;
			while(counter < 20 && resultMoviesMatchingStars.next())
			{
				while(resultMovies.next())
				{
					if(resultMovies.getInt(1) == resultMoviesMatchingStars.getInt(1))
					{
						buf2.append("<TR valign=top>");
						buf2.append("<TD width=150><div class=\"wpmd\">");
						buf2.append("<div>");
						buf2.append("<input type=\"radio\" name=\"movieId\" value=\"" + resultMovies.getInt(1) + "\"> " + "<a href=\"SingleMovieTitle?id="+resultMovies.getInt(1)+"\"> " +resultMovies.getString(2) + "</a>");
						buf2.append("</div>");
						buf2.append("</TD>");
						
					
						buf2.append("<TD width=100><div class=\"wpmd\">");
						buf2.append("<div>");
						buf2.append( resultMovies.getInt(3));
						buf2.append("</div>");
						buf2.append("</TD>");
						
						
						buf2.append("<TD width=150><div class=\"wpmd\">");
						buf2.append("<div>");
						buf2.append(resultMovies.getString(7) + " "+ resultMovies.getString(4));
						buf2.append("</div>");
						buf2.append("</TD>");
						
						String genreAssociated = findGenres(Integer.toString(resultMovies.getInt(1)));
						//genres
						buf2.append("<TD width=150><div class=\"wpmd\">");
						buf2.append("<div>");
						buf2.append(genreAssociated);
						buf2.append("</div>");
						buf2.append("</TD>");
					
	
						String stars = findStars(Integer.toString(resultMovies.getInt(1)));
						//movie stars
						buf2.append("<TD width=200><div class=\"wpmd\">");
						buf2.append("<div>");
						buf2.append(stars);
						buf2.append("</div>");
						buf2.append("</TD>");
					
						buf2.append("</TR>");
						resultMovies.last(); //if match already, then just move to last place.
					}
				}
				resultMovies.beforeFirst(); //move back to beginning;
				counter++;
				
				if(resultMoviesMatchingStars.getRow() == endIndex)
					counter = 20;
			}
			if(!resultMoviesMatchingStars.isAfterLast() && counter == 20)
			{
				if (DEBUG) buf2.append("middle page or beginning page");
				movie_list.setStartIndex(resultMoviesMatchingStars.getRow());
				lastPage = false;
			}
			if((resultMoviesMatchingStars.isLast() &&  counter == 20) || resultMoviesMatchingStars.isAfterLast())
			{		
				int tempInt = movie_list.getStart() + 20;
				movie_list.setStartIndex(tempInt);
				if (DEBUG) buf2.append("last page! Ending list at: " + tempInt);
				if (DEBUG) buf2.append("last page set start index: " + movie_list.getStart());
				lastPage = true;
				movie_list.setState("lastPage");
			}
		
			if (DEBUG) buf2.append("Ending list at : " + movie_list.getStart());
			
			session.setAttribute(Constants.MovieListAttributeName, movie_list);
			connection.close();
		}
		catch(SQLException e)
		{
			buf2.append("SQLException: " + e.getMessage());
		}
		
		return buf2.toString();
	}
	public  String findFeaturedStars(String firstQuery, String featuredStars)
	{
		StringBuffer buf3 = new StringBuffer();
		if (DEBUG) buf3.append("INSIDE FEATURED STARS NEW <br><br>");
		try
		{	
			String first_name = "";
			String last_name = "";
			boolean oneName = false;
			if(featuredStars != null && featuredStars.length() > 0)
			{
				StringTokenizer tokenizer = new StringTokenizer(featuredStars);
				
				int countTokens = tokenizer.countTokens();
				if(countTokens == 1)
				{
					last_name = featuredStars;
					first_name = featuredStars;
					oneName = true;
				}
				else
				{
					while(tokenizer.hasMoreTokens())
					{
						countTokens--;
						if(countTokens == 0)
							last_name = tokenizer.nextToken();
						else
							first_name += tokenizer.nextToken() + " ";
									
					}
				}	
			}
			
			first_name = first_name.trim();
			last_name = last_name.trim();
			
			int first_name_length = first_name.length();
			int last_name_length = last_name.length();
			int LEDAdistance_first = findDistanceLEDA(first_name_length);
			int LEDAdistance_last = findDistanceLEDA(last_name_length);
			
			String query = "";
			if(oneName)
				query += "Select * from stars where first_name ilike '%" + first_name + "%' OR ISCLOSE(first_name, '"+first_name+"', "+LEDAdistance_first+") or last_name ilike '%" + last_name +"%' OR ISCLOSE(last_name, '"+last_name+"', "+LEDAdistance_last+")";
			else
				query += "Select * from stars where ( first_name ilike '%" + first_name + "%' OR ISCLOSE(first_name, '"+first_name+"', "+LEDAdistance_first+") ) and ( last_name ilike '%" + last_name +"%' OR ISCLOSE(last_name, '"+last_name+"', "+LEDAdistance_last+") )";
			
			if(query.length() == 0)
				query += "Select * from stars";
			
			if (DEBUG) buf3.append("Query for starsIds: " + query + "<br><br>");
			
			Statement select8 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			ResultSet resultStars = select8.executeQuery(query);
			
			String queryForMovieIdWithStars = "Select * from stars_in_movies where ";
			
			
			while(resultStars.next())
			{
				if(resultStars.isLast())
					queryForMovieIdWithStars += "star_id = " + resultStars.getInt(1);
				else
					queryForMovieIdWithStars += "star_id = " + resultStars.getInt(1) +" or ";
			}
			
			resultStars.last();
			int size = resultStars.getRow();
			
			
			if(size < 1)
			{
				buf3.append("<font color=\'red\' >Your search has zero results. </font><br>");
				return buf3.toString();
			}
				//queryForMovieIdWithStars = "Select * from stars_in_movies";
				
			if (DEBUG) buf3.append("Query for Movie_ids still in stars_in_movies: " + queryForMovieIdWithStars + "<br><br>");
				
			Statement select9 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			ResultSet resultMovieIds = select9.executeQuery(queryForMovieIdWithStars);
			
		
			
			String queryForMovies = "Select * from movies where ";
			
			while(resultMovieIds.next())
			{
				if(resultMovieIds.isLast())
					queryForMovies += "id = " + resultMovieIds.getInt(2);
				else
					queryForMovies += "id = " + resultMovieIds.getInt(2) +" or ";
			}
			
			String tempQueryForMovies = queryForMovies;
			
			resultMovieIds.last();
			size = resultMovieIds.getRow();
			
			if(size<1)
				queryForMovies = "Select * from movies";
			else
				queryForMovies += " ORDER BY title, year DESC";
			
			if (DEBUG) buf3.append("Query for Movie_ids in ids (associated stars): " + queryForMovies + "<br><br>");
			
			Statement select10 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			ResultSet resultMoviesMatchingStars = select10.executeQuery(queryForMovies);
			
			Statement select11 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			ResultSet resultMovies = select11.executeQuery(firstQuery);
			
			MovieList movie_list = new MovieList();
			movie_list.setMovieListType( Constants.SEARCHING);
			movie_list.setRS(resultMovies);
			movie_list.setRSFeaturedStars(resultMoviesMatchingStars);
			movie_list.setQuery ( firstQuery );
			movie_list.setQueryFeaturedStars(tempQueryForMovies);
			movie_list.setState("firstPage");
			movie_list.setStartIndex(0);
			session.setAttribute(Constants.MovieListAttributeName, movie_list);
		
			startIndex = movie_list.getStart() ;
			endIndex = startIndex + 20;
			if (DEBUG) buf3.append("QUERY 1: " + movie_list.getQuery() +"<br><br>");
			if (DEBUG) buf3.append("QUERY 2: " +movie_list.getQueryFeaturedStars()+"<br><br>");
			if(movie_list.getQuery().equals("Select * from movies") || movie_list.getQueryFeaturedStars().equals("Select * from movies"))
			{
				buf3.append("No movies were found.");
				sizeOfList = 0;
				connection.close();
				return buf3.toString();
			}
			resultMoviesMatchingStars.last();
			this.sizeOfList = resultMoviesMatchingStars.getRow();
			
			resultMoviesMatchingStars.absolute(movie_list.getStart());
			
			int counter = 0;
			int actualMoviesMatchedCounter = 0;
			while(counter < 20 && resultMoviesMatchingStars.next())
			{
				while(resultMovies.next())
				{
					if(resultMovies.getInt(1) == resultMoviesMatchingStars.getInt(1))
					{
						buf3.append("<TR valign=top>");
						buf3.append("<TD width=150><div class=\"wpmd\">");
						buf3.append("<div>");
						buf3.append("<input type=\"radio\" name=\"movieId\" value=\"" + resultMovies.getInt(1) + "\"> " + "<a href=\"SingleMovieTitle?id="+resultMovies.getInt(1)+"\"> " +resultMovies.getString(2) + "</a>");
						buf3.append("</div>");
						buf3.append("</TD>");
						
					
						buf3.append("<TD width=100><div class=\"wpmd\">");
						buf3.append("<div>");
						buf3.append( resultMovies.getInt(3));
						buf3.append("</div>");
						buf3.append("</TD>");
						
						
						buf3.append("<TD width=150><div class=\"wpmd\">");
						buf3.append("<div>");
						buf3.append(resultMovies.getString(7) + " "+ resultMovies.getString(4));
						buf3.append("</div>");
						buf3.append("</TD>");
						
						String genreAssociated = findGenres(Integer.toString(resultMovies.getInt(1)));
						//genres
						buf3.append("<TD width=150><div class=\"wpmd\">");
						buf3.append("<div>");
						buf3.append(genreAssociated);
						buf3.append("</div>");
						buf3.append("</TD>");
					
	
						String stars = findStars(Integer.toString(resultMovies.getInt(1)));
						//movie stars
						buf3.append("<TD width=200><div class=\"wpmd\">");
						buf3.append("<div>");
						buf3.append(stars);
						buf3.append("</div>");
						buf3.append("</TD>");
					
						buf3.append("</TR>");
						resultMovies.last(); //if match already, then just move to last place.
						actualMoviesMatchedCounter++;
					}
				}
				resultMovies.beforeFirst(); //move back to beginning;
				counter++;
				
				if(resultMoviesMatchingStars.getRow() == endIndex)
					counter = 20;
			}
			
			
				//if there are no actual matched movies with featured stars then zero results.
			if(actualMoviesMatchedCounter == 0)
			{
				buf3.append("<font color=\'red\' >Your search has zero results. </font><br>");
				return buf3.toString();
			}
			
			if(!resultMoviesMatchingStars.isAfterLast() && counter == 20)
			{
				if (DEBUG) buf3.append("middle page or beginning page");
				movie_list.setStartIndex(resultMoviesMatchingStars.getRow());
				lastPage = false;
			}
			if((resultMoviesMatchingStars.isLast() &&  counter == 20) || resultMoviesMatchingStars.isAfterLast())
			{		
				int tempInt = movie_list.getStart() + 20;
				movie_list.setStartIndex(tempInt);
				if (DEBUG) buf3.append("last page! Ending list at: " + tempInt);
				if (DEBUG) buf3.append("last page set start index: " + movie_list.getStart());
				lastPage = true;
				movie_list.setState("lastPage");
			}
		
			if (DEBUG) buf3.append("Ending list at : " + movie_list.getStart());
			
			session.setAttribute(Constants.MovieListAttributeName, movie_list);
			
			connection.close();
		}
		catch(SQLException e)
		{
			buf3.append("SQLException: " + e.getMessage());
		}
		return buf3.toString();
		
	}
	public  String findStars(String movieId) throws SQLException
	{
		Statement select2 = connection.createStatement();
		ResultSet resultStarsID = select2.executeQuery("Select star_id from stars_in_movies where movie_id = " + movieId);
		String temp = "";
		
		while(resultStarsID.next())
		{
			Statement select3 = connection.createStatement();
			ResultSet resultStars = select3.executeQuery("Select * from stars where id = " + resultStarsID.getInt(1));
			if(resultStars.next())
			{
				temp += "<a href=\"SingleStarPage?id=" + resultStars.getInt(1) + "\"> " + resultStars.getString(2) + " " + resultStars.getString(3) + " </a><br>";							
			}
			//select3.close();
		}
		//select2.close();
		if(temp.equals(""))
			return "No movie stars";
		return temp;
	}
	// Print HTML for Web page heading
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		if (!Bridge.hasBeenToMainPage(request.getSession(), response.getWriter()))
		{
			return;
		}
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String movieTitle = request.getParameter("title");
		String yearOfRelease = request.getParameter("year");
		String directorName = request.getParameter("directorName");
		String featuredStars = request.getParameter("featuredStars");
		String order = request.getParameter("order");
		String goTo = request.getParameter("goTo");
		
		if(yearOfRelease != null && yearOfRelease.length() > 0)
		{
			if(!isNumber(yearOfRelease))
				yearOfRelease = "-1";
		}
		
		StringBuffer buf = new StringBuffer();
		
		try
		{
			Class.forName("org.postgresql.Driver").newInstance();
			connection = DriverManager.getConnection(
					"jdbc:postgresql://localhost/fabflixs", "testuser", "testpass");
			
			session = request.getSession();
			//redirecting page back to search page
			if(order == null && goTo == null )
			{
				if((movieTitle == null && yearOfRelease == null && directorName == null && featuredStars == null )
						||(movieTitle.length() < 1 && yearOfRelease.length() < 1 && directorName.length() < 1 && featuredStars.length() < 1 ))
				{
					buf.append("<html>");
					buf.append("<head>");
					buf.append("No words were entered to be searched <br>");
					buf.append("<meta http-equiv=\"REFRESH\" content=\"0;url=../Search.jsp\">");
					buf.append("</head>");
					buf.append("</HTML>");
					out.println(buf.toString());
					connection.close();
				}
			}
			 if(movieTitle != null || yearOfRelease != null || directorName != null || featuredStars != null || order != null || goTo != null)
			{
				if (DEBUG) out.println("parameters: title: " + movieTitle + " year: "+yearOfRelease + " director: " + directorName + " stars: "+featuredStars + " goTo: " + goTo + " order: " + order + "<br><br>");
				if (DEBUG) buf.append("will do query <br><br>");
				String query = issueQuery(movieTitle, yearOfRelease, directorName, featuredStars, request);
				if (DEBUG) buf.append("finished query <br><br>");
				//creating form
				buf.append("<form name=\"singleMovieTitle\" action=\"DvdProcessor\" method=\"POST\">");
				//out.println("<div align=\"left\"><br>");
				
				//making table
			
				buf.append("<div><TABLE bgcolor=\"#FFFFFF\" border=1 bordercolorlight=\"#C0C0C0\" bordercolordark=\"#808080\">");
				
				buf.append("<TR valign=top>");
		
			
				buf.append("<TD width=150><div class=\"wpmd\">");
				buf.append("<div>");
				buf.append("<a href=\"SearchForMovies?order=5&start=0&end=20\"><B>TITLE</B></a>");
				buf.append("</div>");
				buf.append("</TD>");
				
				
				buf.append("<TD width=100><div class=\"wpmd\">");
				buf.append("<div>");
				buf.append("<a href=\"SearchForMovies?order=6&start=0&end=20\"><B>YEAR</B></a>");
				buf.append("</div>");
				buf.append("</TD>");
				
				buf.append("<TD width=150><div class=\"wpmd\">");
				buf.append("<div>");
				buf.append("<a href=\"SearchForMovies?order=7&start=0&end=20\"><B>DIRECTOR</B></a>");
				buf.append("</div>");
				buf.append("</TD>");
				
				buf.append("<TD width=150><div class=\"wpmd\">");
				buf.append("<div>");
				buf.append("<B>GENRE</B>");
				buf.append("</div>");
				buf.append("</TD>");
				
				buf.append("<TD width=200><div class=\"wpmd\">");
				buf.append("<div>");
				buf.append("<B>MOVIE STARS</B>");
				buf.append("</div>");
				buf.append("</TD>");
				buf.append("</TR>");
				
				buf.append(query);
				
				buf.append("<TR valign=top>");
	
				buf.append("<TD colspan=5 align=center><div class=\"wpmd\">");
				buf.append("<div id=\"AddToCart\" \"><input type=\"image\" name=\"AddToCart\" src=\"../images/AddToCart.png\"></div>");
				buf.append("</TD>");
				buf.append("</TR>");
				
				
				buf.append("<TR valign=top>");
				
				
				if(sizeOfList <= 20)
				{
					buf.append("<TD colspan=5 align=left ><div class=\"wpmd\">");
					buf.append("<div></div>");
					buf.append("</TD>");
				}
				else if(lastPage)
				{
					startIndex = endIndex - 40;
					if(startIndex < 0)
						startIndex = 0;
					endIndex = startIndex + 20;
					buf.append("<TD colspan=5 align=left ><div class=\"wpmd\">");
					buf.append("<a href=\"SearchForMovies?goTo=2&start=" +startIndex+ "&end=" +endIndex+ "\">");
					buf.append("<div id=\"Prev\" \"><input type=\"image\" name=\"Prev\" src=\"../images/Prev.png\"></div></a>");
					buf.append("</TD>");
					//lastPage = false;
				}
				else if(startIndex != 0 && !lastPage)
				{
					int startIndexPrev, endIndexPrev, startIndexNext, endIndexNext = 0;
					
					startIndexPrev = endIndex - 40;
					if(startIndexPrev < 0)
						startIndexPrev = 0;
					endIndexPrev = startIndexPrev + 20;
					//row for prev and next button
					//buf.append("<TR valign=top>");
					buf.append("<TD colspan=3 align=left ><div class=\"wpmd\">");
					buf.append("<a href=\"SearchForMovies?goTo=2&start=" +startIndexPrev+ "&end=" +endIndexPrev+ "\">");
					buf.append("<div id=\"Prev\" \"><input type=\"image\" name=\"Prev\" src=\"../images/Prev.png\"></div></a>");
					buf.append("</TD>");
				
					
					startIndexNext = endIndex;
					endIndexNext = startIndexNext + 20;
					buf.append("<TD colspan=2 align=right ><div class=\"wpmd\">");
					buf.append("<a href=\"SearchForMovies?goTo=1&start=" +startIndexNext+ "&end=" +endIndexNext+ "\">");
					buf.append("<div id=\"Next\" \"><input type=\"image\" name=\"Next\" src=\"../images/Next.png\"></div></a>");
					buf.append("</TD>");
				}
				else if(startIndex == 0 && !lastPage)
				{
					startIndex = endIndex;
					endIndex = startIndex + 20;
					buf.append("<TD colspan=5 align=right ><div class=\"wpmd\">");
					buf.append("<a href=\"SearchForMovies?goTo=1&start=" +startIndex+ "&end=" +endIndex+ "\">");
					buf.append("<div id=\"Next\" \"><input type=\"image\" name=\"Next\" src=\"../images/Next.png\"></div></a>");
					buf.append("</TD>");
					
				}
				
				buf.append("</TR>");
				
				
				buf.append("</TABLE>");
				buf.append("</div>");
		
				buf.append("</form>");	
				out.println(Template.getTemplateHTML("Movies Associated with Genre", buf.toString(),
						Constants.straightToCart, request.getSession() ));
			}
		
		}
		catch (SQLException sqle)
		{
			buf.append("SQL exception occured");
			out.println("SQL exception occured: " + sqle.getMessage());
		}	
		catch (ClassNotFoundException cnfe)
		{
			buf.append("ClassNotFound exception occured");
			out.println("ClassNotFound exception occured: " + cnfe.getMessage());
		}
		catch (InstantiationException ie)
		{
			buf.append("Instantiation exception occured");
			out.println("ClassNotFound exception occuredL " + ie.getMessage());
		}
		catch (IllegalAccessException iae)
		{
			buf.append("IllegalAccess exception occured");
			out.println("ClassNotFound exception occured: " + iae.getMessage());
		}
		catch(Exception e)
		{
			out.println("Other exception occured: " + e.getMessage());	
		}
	
	}
	
	// Upon init of servlet, open the moviedb database
	public void init() 
	{
	}

	private static boolean isNumber(String str)
	{
		try{
			Integer.parseInt(str);
		} catch (Exception e)
		{
			return false;
		}
		return true;
	}
	
}


